package main.java.com.introduce.extract;

import main.java.com.introduce.Entry;
import main.java.com.introduce.annotation.ExtractAfter;

import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;

/**
 * @description: 重构之引入参数对象
 * 单纯的提炼和搬移动作
 * @author: cong zhi
 * @createDate: 2022/5/26 8:28
 * @updateUser: cong zhi
 * @updateDate: 2022/5/26 8:28
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@ExtractAfter
public class Account {

    /**
     * 将DateRange 对象加到getFlowBetween() 函数的参数列中：
     * <p>
     * TODO:下一个步骤是去除旧参数之一，以新建对象取而代之。首先我删除start 参数，
     * TODO: 并修改getFlowBetween() 函数及其调用者，让它们转而使用新对象：
     *
     * @param start
     * @param end
     * @param range
     * @return
     */
    @ExtractAfter
    double getFlowBetween(Date start, Date end, DateRange range) {
        double result = 0;
        Enumeration e = entries.elements();
        while (e.hasMoreElements()) {
            Entry each = (Entry) e.nextElement();
            if (each.getDate().equals(start) ||
                    each.getDate().equals(end) ||
                    (each.getDate().after(start) && each.getDate().before(end))) {
                result += each.getValue();
            }
        }
        return result;
    }

    /**
     * 以新建对象取而代之。首先我删除start 参数，
     *
     * @param end
     * @param range
     * @return
     */
    @ExtractAfter
    double getFlowBetween(Date end, DateRange range) {
        double result = 0;
        Enumeration e = entries.elements();
        while (e.hasMoreElements()) {
            Entry each = (Entry) e.nextElement();
            if (each.getDate().equals(range.getStart()) ||
                    each.getDate().equals(end) ||
                    (each.getDate().after(range.getStart()) && each.getDate().before(end))) {
                result += each.getValue();
            }
        }
        return result;
    }

    /**
     * 将end参数也移除
     *
     * @param range
     * @return
     */
    @ExtractAfter
    double getFlowBetween(DateRange range) {
        double result = 0;
        Enumeration e = entries.elements();
        while (e.hasMoreElements()) {
            Entry each = (Entry) e.nextElement();
            if (each.getDate().equals(range.getStart()) ||
                    each.getDate().equals(range.getEnd()) ||
                    (each.getDate().after(range.getStart()) && each.getDate().before(range.getEnd()))) {
                result += each.getValue();
            }
        }
        return result;
    }

    /**
     * 可以将适当的行为从其他函数移到这个新建对象中，进一步从本项重构获得更大利益
     */
    @ExtractAfter
    double flowBetween(DateRange range) {
        double result = 0;
        Enumeration e = entries.elements();
        while (e.hasMoreElements()) {
            Entry each = (Entry) e.nextElement();
            if (range.includes(each.getDate())) {
                result += each.getValue();
            }
        }
        return result;
    }

    private Vector entries = new Vector();
}
